package com.example.hutool;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateRange;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取节假日
 *
 * @author 江黎
 * @since 2023-12-04
 */
public class Holiday {

    public static final String holidayUrl = "https://tool.bitefu.net/jiari/?d=";

    public static final String sql = "insert into ATTENDCENTER_HOLIDAY (HOLIDAY_ID, TB_UUID, COUNTRY, HOLIDAY_DATE, REMARK, IS_DELETED, IS_LEGAL_HOLIDAY) values (SMARTOFFICE.SEQ_HOLIDAY_ID.nextval, lower(sys_guid()), 'China', '%s', '%s', 0, %s);";


    public static void main(String[] args) {
        String response = HttpUtil.get("https://date.appworlds.cn/year/2024");
        JSON json = JSONUtil.parse(response);
        String data = json.getByPath("data", String.class);
        List<JSONObject> jsonObjectList = JSONUtil.toList(data, JSONObject.class);

        Map<String, String> festivalMap = new HashMap<>();
        for (JSONObject jsonObject : jsonObjectList) {
            Boolean holiday = jsonObject.getBool("holiday");
            if (holiday) {
                String date = jsonObject.getStr("date");
                String name = jsonObject.getStr("name");
                festivalMap.put(date, name);
            }
        }
        System.out.println(festivalMap);

        DateTime nextTime = DateUtil.parse("2024-01-01");
        Date begin = DateUtil.beginOfYear(nextTime);
        Date end = DateUtil.endOfYear(nextTime);
        DateRange range = DateUtil.range(begin, end, DateField.DAY_OF_YEAR);

        for (DateTime dateTime : range) {
            String dateStr = DateUtil.formatDate(dateTime);
            response = HttpUtil.get(holidayUrl + dateStr);
            // 0：工作日，1：周末，2：节假日
            if ("1".equals(response) || "2".equals(response)) {
                String name = festivalMap.get(dateStr);
                // 法定节假日
                if (StrUtil.isNotBlank(name)) {
                    System.out.println(String.format(sql, dateStr, name, 1));
                } else {
                    // 周末
                    String week = DateUtil.dayOfWeekEnum(DateUtil.parse(dateStr)).toChinese();
                    System.out.println(String.format(sql, dateStr, week, 0));
                }
            }
        }

    }
}
